from influxdb import InfluxDBClient
from base_db import create_data

'''
Author: Guoliang Liu
Date: 20230829
'''


def search_num(IP, PID, IDS, influxDB_name,influxDB_table):
    # cd = create_data()
    # 需要造数的机器IP （也是数据库IP）
    influxDB_IP = IP
    # 工程 ID
    measurement_value = PID
    # 数据点对应 ids
    path_value = IDS
    # 查询结果保存在 searchResult.txt文件中
    influxDB_name = influxDB_name
    influxDB_table = influxDB_table
    # 连接数据库
    client = InfluxDBClient(influxDB_IP, 8086, influxDB_name, '', influxDB_table, ssl=True)
    print("[INFO] 查询数据所在机器：" + influxDB_IP)
    search_data(measurement_value, path_value, client, influxDB_table)
    client.close()


def search_data(PID, IDS, client, influxDB_table):
    print("[INFO] 调用search方法查询数据，结果保存在 searchResult.txt 文件中")
    sql = "SELECT * FROM \"" + PID + "\" WHERE Path='" + IDS + "';"
    print(sql)
    res = client.query(
        sql,
        database=influxDB_table)
    if res:
        result = list(res)[0]
        file = "searchResult.txt"
        with open(file, "w", encoding='utf-8') as f:
            for i in result:
                f.write(str(i) + "\n")
            f.write("[INFO] 数据个数： " + str(len(result)))
            print("[INFO] 数据个数： " + str(len(result)))
    else:
        file = "searchResult.txt"
        with open(file, "w", encoding='utf-8') as f:
            f.write("[INFO] 查询数据个数： 0")
            print("[INFO] 查询数据个数： 0")


if __name__ == '__main__':
    search_num()
